package com.ae.shield.common.net.toSever;

import com.ae.shield.api.IButtonHandler;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.network.NetworkEvent;

import java.util.function.Supplier;

public class ScreenButtonPressed {
    private final BlockPos pos;
    private final int button;

    public ScreenButtonPressed(BlockPos pos, int button) {
        this.button = button;
        this.pos = pos;
    }

    public static void encode(ScreenButtonPressed msg, PacketBuffer buffer) {
        buffer.writeBlockPos(msg.pos);
        buffer.writeInt(msg.button);
    }

    public static ScreenButtonPressed decode(PacketBuffer buffer) {
        return new ScreenButtonPressed(buffer.readBlockPos(), buffer.readInt());
    }

    public static void handle(ScreenButtonPressed packet, Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        context.enqueueWork(() -> {
            ServerPlayerEntity player = context.getSender();
            if (player != null) {
                BlockPos pos = packet.pos;
                int button = packet.button;
                TileEntity tile = player.world.getTileEntity(pos);
                if (tile instanceof IButtonHandler) {
                    ((IButtonHandler) tile).onButtonPressed(button);
                }
            }
        });
        context.setPacketHandled(true);
    }
}
